import Vue from "vue"
import Vuex from 'vuex'
Vue.use(Vuex)
import { logout } from '../api/login.js'


export default new Vuex.Store({
	state: {
		token: null,
		user: null,
		downlist: [], // 下载任务列表
		uploadList:[], // 上传任务列表
	},
	actions: {
		// 登录
		login({state},user) {
			// console.log('user:',user);
			state.token = user.token
			state.user = user
			// console.log(' user.token:', user.token);
			uni.setStorageSync('user',JSON.stringify(user))
			uni.setStorageSync('token', user.token)
		},
		
		// 初始化用户信息
		initUser({state}) {
			let user = uni.getStorageSync('user')
			if(user){
				state.user = JSON.parse(user)
				state.token = state.user.token
			}
		},
		
		// 更新内存
		updateSize({state}, data){
			state.user.total_size = data.total_size
			stage.user.used_size = data.used_size
		},
		
		// 退出登录
		async logout({state}) {
			let res = await logout({},{token: true})
			state.user = null
			state.token = null
			uni.removeStorageSync('user')
			uni.removeStorageSync('token')
			uni.reLaunch({
				url: '/pages/login/login'
			})
		},
		
		// 创建上传任务
		createUploadJob({state}, obj) {
			state.uploadList.unshift(obj)
			uni.setStorage({
				key:'uploadList_'+ state.user.id,
				data: JSON.stringify(state.uploadList)
			})
		},
		
		// 更新上传任务进度
		updateUploadJob({state}, obj) {
			let i = state.uploadList.findIndex(item => item.key == obj.key)
			if(i != -1){
				state.uploadList[i].progress = obj.progress				state.uploadList[i].status = obj.status
				uni.setStorage({
					key:'uploadList' + state.user.id,
					data: JSON.stringify(state.uploadList)
				})
			}
		},
		
		// 创建下载任务
		creatDownLoadJob({state}, obj) {
			state.downlist.unshift(obj)
			uni.setStorage({
				key: 'downlist_'+ state.user.id,
				data: JSON.stringify(state.downlist)
			})
		},
		
		//更新下载任务进度
		updateDownLoadJob({state},obj) {
			let i = state.downlist.findIndex(item => item.key == obj.key)
			if(i != -1){
				state.downlist[i].progress = obj.progress
				state.downlist[i].status = obj.status
				uni.setStorage({
					key: 'downlist_' + state.user.id,
					data: JSON.stringify(state.uploadlist)
				})
			}
		}
		
		
	}
})